<template>
  <div class="parking-management-container">
    <el-card class="page-header-card">
      <div class="page-header">
        <div class="page-title">
          <h2>停车场管理</h2>
          <p>管理系统中的停车场和车位信息</p>
        </div>
        <div class="page-actions">
          <el-button-group>
            <el-button type="primary" @click="activeTab = 'parking-list'">
              <el-icon><Setting /></el-icon> 停车场列表
            </el-button>
            <el-button type="primary" @click="activeTab = 'parking-spaces'">
              <el-icon><Location /></el-icon> 车位管理
            </el-button>
          </el-button-group>
          <el-button v-if="activeTab === 'parking-list'" type="success" @click="showAddParkingDialog">
            <el-icon><Plus /></el-icon> 添加停车场
          </el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 停车场列表 -->
    <div v-if="activeTab === 'parking-list'">
      <!-- 停车场筛选 -->
      <el-card class="filter-card">
        <div class="filter-container">
          <el-form :inline="true" :model="parkingFilterForm" class="filter-form">
            <el-form-item label="停车场名称">
              <el-input
                v-model="parkingFilterForm.name"
                placeholder="输入停车场名称"
                clearable
                @keyup.enter="handleParkingFilter"
                @clear="handleParkingFilter"
              />
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="parkingFilterForm.status"
                placeholder="选择状态"
                clearable
                @change="handleParkingFilter"
              >
                <el-option label="营业中" :value="1" />
                <el-option label="维护中" :value="2" />
                <el-option label="已关闭" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleParkingFilter">筛选</el-button>
              <el-button @click="resetParkingFilter">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      
      <!-- 停车场列表 -->
      <el-card class="parking-list-card">
        <div v-loading="parkingListLoading">
          <el-table
            :data="parkingList"
            border
            style="width: 100%"
            @row-click="handleParkingRowClick"
          >
            <el-table-column prop="id" label="ID" width="80" sortable />
            <el-table-column prop="name" label="停车场名称" min-width="150" show-overflow-tooltip />
            <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
            <el-table-column prop="totalSpaces" label="总车位数" width="100" sortable />
            <el-table-column label="剩余车位" width="100" sortable>
              <template #default="scope">
                <span>{{ scope.row.availableSpaces }}</span>
                <el-progress 
                  :percentage="Math.round((scope.row.availableSpaces / scope.row.totalSpaces) * 100)" 
                  :status="getSpaceProgressStatus(scope.row.availableSpaces, scope.row.totalSpaces)" 
                  :stroke-width="5" 
                  class="space-progress"
                />
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getParkingStatusType(scope.row.status)">
                  {{ getParkingStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="180" />
            <el-table-column label="操作" width="250" fixed="right">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click.stop="handleEditParking(scope.row)"
                >编辑</el-button>
                <el-button
                  :type="scope.row.status === 1 ? 'warning' : 'success'"
                  size="small"
                  @click.stop="handleToggleParkingStatus(scope.row)"
                >{{ scope.row.status === 1 ? '设为维护' : scope.row.status === 2 ? '恢复营业' : '启用' }}</el-button>
                <el-button
                  v-if="scope.row.status !== 0"
                  type="danger"
                  size="small"
                  @click.stop="handleCloseParking(scope.row)"
                >关闭</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="parkingCurrentPage"
              v-model:page-size="parkingPageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="parkingTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleParkingSizeChange"
              @current-change="handleParkingCurrentChange"
            />
          </div>
        </div>
        
        <!-- 空数据展示 -->
        <el-empty v-if="parkingList.length === 0 && !parkingListLoading" description="暂无停车场数据" />
      </el-card>
      
      <!-- 添加/编辑停车场对话框 -->
      <el-dialog
        v-model="parkingDialog.visible"
        :title="parkingDialog.isEdit ? '编辑停车场' : '添加停车场'"
        width="650px"
        @close="resetParkingForm"
      >
        <el-form
          ref="parkingFormRef"
          :model="parkingForm"
          :rules="parkingRules"
          label-width="100px"
        >
          <el-form-item label="停车场名称" prop="name">
            <el-input v-model="parkingForm.name" placeholder="请输入停车场名称" />
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="parkingForm.address" placeholder="请输入详细地址" />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="总车位数" prop="totalSpaces">
                <el-input-number v-model="parkingForm.totalSpaces" :min="1" :max="10000" controls-position="right" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="剩余车位" prop="availableSpaces">
                <el-input-number v-model="parkingForm.availableSpaces" :min="0" :max="parkingForm.totalSpaces" controls-position="right" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="营业状态" prop="status">
            <el-radio-group v-model="parkingForm.status">
              <el-radio :label="1">营业中</el-radio>
              <el-radio :label="2">维护中</el-radio>
              <el-radio :label="0">已关闭</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="parkingForm.contactPhone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="营业时间" prop="businessHours">
            <el-input v-model="parkingForm.businessHours" placeholder="如: 24小时营业 或 08:00-22:00" />
          </el-form-item>
          <el-form-item label="备注信息" prop="description">
            <el-input
              v-model="parkingForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="parkingDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="submitParkingForm" :loading="parkingSubmitting">
              {{ parkingDialog.isEdit ? '保存' : '添加' }}
            </el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 停车场详情抽屉 -->
      <el-drawer
        v-model="parkingDetailVisible"
        :title="currentParking ? currentParking.name + ' 详情' : '停车场详情'"
        direction="rtl"
        size="500px"
      >
        <div v-if="currentParking" class="parking-detail-content">
          <div class="detail-section">
            <h4 class="section-title">基本信息</h4>
            <div class="info-item">
              <span class="info-label">停车场ID</span>
              <span class="info-value">{{ currentParking.id }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">停车场名称</span>
              <span class="info-value">{{ currentParking.name }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">详细地址</span>
              <span class="info-value">{{ currentParking.address }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">状态</span>
              <span class="info-value">
                <el-tag :type="getParkingStatusType(currentParking.status)">
                  {{ getParkingStatusText(currentParking.status) }}
                </el-tag>
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">联系电话</span>
              <span class="info-value">{{ currentParking.contactPhone }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">营业时间</span>
              <span class="info-value">{{ currentParking.businessHours }}</span>
            </div>
          </div>
          
          <div class="detail-section">
            <h4 class="section-title">车位信息</h4>
            <div class="spaces-overview">
              <div class="space-stat-item">
                <div class="stat-value">{{ currentParking.totalSpaces }}</div>
                <div class="stat-label">总车位数</div>
              </div>
              <div class="space-stat-item">
                <div class="stat-value">{{ currentParking.availableSpaces }}</div>
                <div class="stat-label">剩余车位</div>
              </div>
              <div class="space-stat-item">
                <div class="stat-value">{{ currentParking.totalSpaces - currentParking.availableSpaces }}</div>
                <div class="stat-label">已占用</div>
              </div>
            </div>
            <div class="space-usage">
              <span class="usage-label">车位占用率</span>
              <el-progress 
                :percentage="Math.round(((currentParking.totalSpaces - currentParking.availableSpaces) / currentParking.totalSpaces) * 100)" 
                :format="percent => percent + '%'"
                :status="getOccupancyStatus(currentParking.availableSpaces, currentParking.totalSpaces)" 
              />
            </div>
          </div>
          
          <div class="detail-section">
            <h4 class="section-title">备注信息</h4>
            <div class="description-content">
              {{ currentParking.description || '暂无备注信息' }}
            </div>
          </div>
          
          <div class="action-buttons">
            <el-button type="primary" @click="handleEditParking(currentParking)">编辑信息</el-button>
            <el-button
              :type="currentParking.status === 1 ? 'warning' : 'success'"
              @click="handleToggleParkingStatus(currentParking)"
            >{{ currentParking.status === 1 ? '设为维护' : currentParking.status === 2 ? '恢复营业' : '启用' }}</el-button>
          </div>
        </div>
      </el-drawer>
    </div>
    
    <!-- 车位管理 -->
    <div v-if="activeTab === 'parking-spaces'">
      <!-- 车位筛选 -->
      <el-card class="filter-card">
        <div class="filter-container">
          <el-form :inline="true" :model="spaceFilterForm" class="filter-form">
            <el-form-item label="停车场">
              <el-select
                v-model="spaceFilterForm.parkingLotId"
                placeholder="选择停车场"
                clearable
                @change="handleSpaceFilter"
              >
                <el-option
                  v-for="item in activeParkingLots"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="区域">
              <el-select
                v-model="spaceFilterForm.area"
                placeholder="选择区域"
                clearable
                @change="handleSpaceFilter"
              >
                <el-option label="A区" value="A" />
                <el-option label="B区" value="B" />
                <el-option label="C区" value="C" />
                <el-option label="D区" value="D" />
              </el-select>
            </el-form-item>
            <el-form-item label="车位编号">
              <el-input
                v-model="spaceFilterForm.spaceNumber"
                placeholder="输入车位编号"
                clearable
                @keyup.enter="handleSpaceFilter"
                @clear="handleSpaceFilter"
              />
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="spaceFilterForm.status"
                placeholder="选择状态"
                clearable
                @change="handleSpaceFilter"
              >
                <el-option label="空闲" :value="0" />
                <el-option label="已占用" :value="1" />
                <el-option label="已预约" :value="2" />
                <el-option label="维护中" :value="3" />
                <el-option label="已禁用" :value="4" />
              </el-select>
            </el-form-item>
            <el-form-item label="车位类型">
              <el-select
                v-model="spaceFilterForm.spaceType"
                placeholder="选择类型"
                clearable
                @change="handleSpaceFilter"
              >
                <el-option label="普通车位" :value="0" />
                <el-option label="固定车位" :value="1" />
                <el-option label="访客车位" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSpaceFilter">筛选</el-button>
              <el-button @click="resetSpaceFilter">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      
      <!-- 操作按钮 -->
      <el-card class="action-card">
        <div class="action-container">
          <el-button-group>
            <el-button type="primary" @click="showAddSpaceDialog">
              <el-icon><Plus /></el-icon> 新增车位
            </el-button>
            <el-button type="info" @click="showSpaceMapDialog">
              <el-icon><MapLocation /></el-icon> 车位地图
            </el-button>
          </el-button-group>
          
          <el-button-group>
            <el-button type="warning" @click="batchMaintainSpaces" :disabled="!selectedSpaces.length">
              <el-icon><Tools /></el-icon> 批量维护
            </el-button>
            <el-button type="danger" @click="batchDisableSpaces" :disabled="!selectedSpaces.length">
              <el-icon><RemoveFilled /></el-icon> 批量禁用
            </el-button>
          </el-button-group>
        </div>
      </el-card>
      
      <!-- 车位列表 -->
      <el-card class="parking-space-card">
        <div v-loading="spaceListLoading">
          <el-table
            :data="spaceList"
            border
            style="width: 100%"
            @selection-change="handleSpaceSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="ID" width="80" sortable />
            <el-table-column prop="spaceNumber" label="车位编号" width="120" />
            <el-table-column prop="parkingLotName" label="所属停车场" width="180" show-overflow-tooltip />
            <el-table-column prop="area" label="区域" width="80" />
            <el-table-column prop="floor" label="楼层" width="80" />
            <el-table-column label="车位类型" width="100">
              <template #default="scope">
                <el-tag :type="getSpaceTypeColor(scope.row.spaceType)">
                  {{ getSpaceTypeName(scope.row.spaceType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getSpaceStatusColor(scope.row.status)">
                  {{ getSpaceStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="plateNumber" label="当前车牌" width="120" />
            <el-table-column prop="entryTime" label="入场时间" width="180" />
            <el-table-column prop="remarks" label="备注信息" min-width="150" show-overflow-tooltip />
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleEditSpace(scope.row)"
                >编辑</el-button>
                <el-button
                  v-if="scope.row.status === 0 || scope.row.status === 3 || scope.row.status === 4"
                  :type="scope.row.status === 3 ? 'success' : scope.row.status === 4 ? 'success' : 'warning'"
                  size="small"
                  @click="handleToggleSpaceStatus(scope.row)"
                >{{ scope.row.status === 3 ? '恢复使用' : scope.row.status === 4 ? '恢复使用' : '设为维护' }}</el-button>
                <el-button
                  v-if="scope.row.status === 0 || scope.row.status === 3"
                  type="danger"
                  size="small"
                  @click="handleDisableSpace(scope.row)"
                >禁用</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="spaceCurrentPage"
              v-model:page-size="spacePageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="spaceTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSpaceSizeChange"
              @current-change="handleSpaceCurrentChange"
            />
          </div>
        </div>
        
        <!-- 空数据展示 -->
        <el-empty v-if="spaceList.length === 0 && !spaceListLoading" description="暂无车位数据" />
      </el-card>
      
      <!-- 添加/编辑车位对话框 -->
      <el-dialog
        v-model="spaceDialog.visible"
        :title="spaceDialog.isEdit ? '编辑车位' : '添加车位'"
        width="600px"
        @close="resetSpaceForm"
      >
        <el-form
          ref="spaceFormRef"
          :model="spaceForm"
          :rules="spaceRules"
          label-width="100px"
        >
          <el-form-item label="停车场" prop="parkingLotId">
            <el-select v-model="spaceForm.parkingLotId" placeholder="请选择停车场" style="width: 100%">
              <el-option
                v-for="item in activeParkingLots"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="区域" prop="area">
                <el-select v-model="spaceForm.area" placeholder="请选择区域" style="width: 100%">
                  <el-option label="A区" value="A" />
                  <el-option label="B区" value="B" />
                  <el-option label="C区" value="C" />
                  <el-option label="D区" value="D" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车位编号" prop="spaceNumber">
                <el-input v-model="spaceForm.spaceNumber" placeholder="请输入车位编号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="车位类型" prop="spaceType">
            <el-select v-model="spaceForm.spaceType" placeholder="请选择车位类型" style="width: 100%">
              <el-option label="普通车位" :value="0" />
              <el-option label="固定车位" :value="1" />
              <el-option label="访客车位" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="车位状态" prop="status">
            <el-select v-model="spaceForm.status" placeholder="请选择车位状态" style="width: 100%">
              <el-option label="空闲" :value="0" />
              <el-option label="维护中" :value="3" />
              <el-option label="已禁用" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="所在楼层" prop="floor">
            <el-input v-model="spaceForm.floor" placeholder="请输入所在楼层" />
          </el-form-item>
          <el-form-item label="备注信息" prop="remarks">
            <el-input
              v-model="spaceForm.remarks"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="spaceDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="submitSpaceForm" :loading="spaceSubmitting">
              {{ spaceDialog.isEdit ? '保存' : '添加' }}
            </el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 批量导入车位对话框 -->
      <el-dialog
        v-model="importDialog.visible"
        title="批量导入车位"
        width="650px"
      >
        <div class="import-container">
          <el-alert
            title="请按照模板格式准备导入数据"
            type="info"
            description="支持Excel文件导入，导入前请确保数据格式正确，点击下方按钮下载模板"
            show-icon
            :closable="false"
            style="margin-bottom: 20px"
          />
          
          <el-form
            :model="importForm"
            label-width="120px"
          >
            <el-form-item label="停车场">
              <el-select v-model="importForm.parkingId" placeholder="请选择停车场" style="width: 100%">
                <el-option
                  v-for="item in activeParkingLots"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="上传文件">
              <el-upload
                class="upload-demo"
                drag
                action="#"
                :auto-upload="false"
                :limit="1"
                :on-change="handleImportFileChange"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    只能上传xlsx/xls文件，且不超过10MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
          
          <div class="download-template">
            <el-button type="info" size="small" plain>
              <el-icon><Download /></el-icon> 下载模板
            </el-button>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="importDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="submitImport" :loading="importDialog.loading" :disabled="!importForm.file">
              开始导入
            </el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 车位地图对话框 -->
      <el-dialog
        v-model="mapDialog.visible"
        title="车位地图"
        width="90%"
        fullscreen
      >
        <div class="map-dialog-container">
          <div class="map-filter">
            <el-form :inline="true">
              <el-form-item label="停车场">
                <el-select v-model="mapDialog.parkingId" placeholder="选择停车场" @change="handleMapParkingChange">
                  <el-option
                    v-for="item in activeParkingLots"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="区域">
                <el-select v-model="mapDialog.area" placeholder="选择区域" @change="handleMapAreaChange">
                  <el-option label="全部区域" value="" />
                  <el-option
                    v-for="area in mapAreas"
                    :key="area"
                    :label="`${area}区`"
                    :value="area"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          
          <div class="map-status-legend">
            <div class="legend-item">
              <div class="legend-color bg-free"></div>
              <span class="legend-text">空闲</span>
            </div>
            <div class="legend-item">
              <div class="legend-color bg-occupied"></div>
              <span class="legend-text">已占用</span>
            </div>
            <div class="legend-item">
              <div class="legend-color bg-reserved"></div>
              <span class="legend-text">已预约</span>
            </div>
            <div class="legend-item">
              <div class="legend-color bg-maintenance"></div>
              <span class="legend-text">维护中</span>
            </div>
            <div class="legend-item">
              <div class="legend-color bg-disabled"></div>
              <span class="legend-text">已禁用</span>
            </div>
          </div>
          
          <div class="map-container">
            <div v-if="mapDialog.loading" class="map-loading">
              <el-icon class="is-loading" :size="48"><Loading /></el-icon>
              <p>加载车位数据中...</p>
            </div>
            <div v-else-if="!mapDialog.parkingId" class="map-empty">
              <el-empty description="请选择停车场查看车位地图"></el-empty>
            </div>
            <div v-else-if="mapDialog.mapSpaces.length === 0" class="map-empty">
              <el-empty description="暂无车位数据"></el-empty>
            </div>
            <div v-else class="parking-map">
              <div v-for="area in mapAreas" :key="area" class="map-area">
                <div class="area-title">{{ area }}区</div>
                <div class="area-spaces">
                  <div
                    v-for="space in getMapSpacesByArea(area)"
                    :key="space.id"
                    class="space-item"
                    :class="getSpaceItemClass(space.status)"
                    @click="handleMapSpaceClick(space)"
                  >
                    <div class="space-code">{{ space.spaceNumber }}</div>
                    <div v-if="space.status === 1" class="space-plate">{{ space.plateNumber || '无牌照' }}</div>
                    <div v-if="space.spaceType !== 0" class="space-type-icon">
                      <el-icon v-if="space.spaceType === 1"><Cpu /></el-icon>
                      <el-icon v-if="space.spaceType === 2"><SemiSelect /></el-icon>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-dialog>
      
      <!-- 车位详情对话框 -->
      <el-dialog
        v-model="spaceDetailDialog.visible"
        :title="`车位 ${spaceDetailDialog.space?.spaceNumber || ''} 详情`"
        width="500px"
      >
        <div v-if="spaceDetailDialog.space" class="space-detail-content">
          <div class="detail-item">
            <span class="detail-label">车位编号</span>
            <span class="detail-value">{{ spaceDetailDialog.space.spaceNumber }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">所属停车场</span>
            <span class="detail-value">{{ spaceDetailDialog.space.parkingLotName }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">区域</span>
            <span class="detail-value">{{ spaceDetailDialog.space.area }}区</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">楼层</span>
            <span class="detail-value">{{ spaceDetailDialog.space.floor }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">车位类型</span>
            <span class="detail-value">
              <el-tag :type="getSpaceTypeColor(spaceDetailDialog.space.spaceType)">
                {{ getSpaceTypeName(spaceDetailDialog.space.spaceType) }}
              </el-tag>
            </span>
          </div>
          <div class="detail-item">
            <span class="detail-label">状态</span>
            <span class="detail-value">
              <el-tag :type="getSpaceStatusColor(spaceDetailDialog.space.status)">
                {{ getSpaceStatusText(spaceDetailDialog.space.status) }}
              </el-tag>
            </span>
          </div>
          
          <template v-if="spaceDetailDialog.space.status === 1">
            <div class="detail-divider"></div>
            <div class="detail-item">
              <span class="detail-label">当前车牌</span>
              <span class="detail-value">{{ spaceDetailDialog.space.plateNumber }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">入场时间</span>
              <span class="detail-value">{{ spaceDetailDialog.space.entryTime }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">停车时长</span>
              <span class="detail-value">{{ calculateDuration(spaceDetailDialog.space.entryTime) }}</span>
            </div>
          </template>
          
          <div class="detail-divider"></div>
          <div class="detail-item">
            <span class="detail-label">备注信息</span>
            <span class="detail-value remarks">{{ spaceDetailDialog.space.remarks || '无' }}</span>
          </div>
        </div>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="spaceDetailDialog.visible = false">关闭</el-button>
            <el-button type="primary" @click="handleEditSpace(spaceDetailDialog.space)">编辑车位</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    
    <!-- 收费标准 -->
    <div v-if="activeTab === 'pricing'" class="placeholder-content">
      <el-empty description="收费标准管理功能开发中，敬请期待...">
        <template #image>
          <el-icon :size="60" class="under-development-icon"><Money /></el-icon>
        </template>
        <el-button type="primary" @click="activeTab = 'parking-list'">返回停车场列表</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Setting, Location, Money, Plus, Edit, Delete, 
  View, Tools, WarningFilled, Check, Close, Upload, MapLocation, RemoveFilled, Download, Loading,
  Cpu, SemiSelect, Star, UploadFilled
} from '@element-plus/icons-vue'
import { 
  getParkingLotList, 
  getParkingLotDetail, 
  addParkingLot, 
  updateParkingLot, 
  deleteParkingLot,
  getParkingSpaceList, 
  getParkingSpaceDetail,
  getParkingSpacesByLotId,
  addParkingSpace, 
  updateParkingSpace, 
  deleteParkingSpace,
  batchAddParkingSpaces,
  checkSpaceNumberExists
} from '@/api/parking'

// 当前活动标签
const activeTab = ref('parking-list')

// 监听标签切换
watch(activeTab, (newValue) => {
  if (newValue === 'parking-spaces') {
    fetchSpaceList()
  }
})

// 活跃的停车场列表（用于选择器）
const activeParkingLots = computed(() => {
  return parkingList.value.filter(item => item.status !== 0)
})

// ========== 停车场列表相关 ==========
// 列表数据
const parkingList = ref([])
const parkingListLoading = ref(false)
const parkingCurrentPage = ref(1)
const parkingPageSize = ref(10)
const parkingTotal = ref(0)

// 筛选表单
const parkingFilterForm = reactive({
  name: '',
  status: '',
  page: 1,
  pageSize: 10
})

// 对话框状态
const parkingDialog = reactive({
  visible: false,
  isEdit: false
})

// 表单引用
const parkingFormRef = ref(null)

// 表单数据
const parkingForm = reactive({
  id: '',
  name: '',
  address: '',
  totalSpaces: 100,
  availableSpaces: 100,
  status: 1,
  contactPhone: '',
  businessHours: '24小时营业',
  description: ''
})

// 表单验证规则
const parkingRules = {
  name: [
    { required: true, message: '请输入停车场名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  totalSpaces: [
    { required: true, message: '请输入总车位数', trigger: 'blur' },
    { type: 'number', min: 1, message: '总车位数不能小于1', trigger: 'blur' }
  ],
  availableSpaces: [
    { required: true, message: '请输入剩余车位数', trigger: 'blur' },
    { type: 'number', min: 0, message: '剩余车位数不能为负数', trigger: 'blur' }
  ],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-\d{7,8}$/, message: '请输入正确的联系电话', trigger: 'blur' }
  ]
}

// 提交状态
const parkingSubmitting = ref(false)

// 停车场详情抽屉
const parkingDetailVisible = ref(false)
const currentParking = ref(null)

// 获取停车场状态文本
const getParkingStatusText = (status) => {
  switch (status) {
    case 0: return '已关闭'
    case 1: return '营业中'
    case 2: return '维护中'
    default: return '未知状态'
  }
}

// 获取停车场状态类型
const getParkingStatusType = (status) => {
  switch (status) {
    case 0: return 'danger'
    case 1: return 'success'
    case 2: return 'warning'
    default: return 'info'
  }
}

// 获取车位进度条状态
const getSpaceProgressStatus = (available, total) => {
  const percentage = (available / total) * 100
  if (percentage <= 20) return 'exception'
  if (percentage <= 50) return 'warning'
  return 'success'
}

// 获取车位占用状态
const getOccupancyStatus = (available, total) => {
  const occupancyRate = ((total - available) / total) * 100
  if (occupancyRate >= 80) return 'exception'
  if (occupancyRate >= 50) return 'warning'
  return 'success'
}

// 监听总车位数变化，确保剩余车位不超过总车位
watch(() => parkingForm.totalSpaces, (newValue) => {
  if (parkingForm.availableSpaces > newValue) {
    parkingForm.availableSpaces = newValue
  }
})

// 获取停车场列表
const fetchParkingList = () => {
  parkingListLoading.value = true
  
  const params = {
    page: parkingFilterForm.page,
    size: parkingFilterForm.pageSize
  }
  
  // 添加过滤条件
  if (parkingFilterForm.name) {
    params.name = parkingFilterForm.name
  }
  
  if (parkingFilterForm.status !== null && parkingFilterForm.status !== undefined) {
    params.status = parkingFilterForm.status
  }
  
  getParkingLotList(params)
    .then(response => {
      parkingList.value = response.data.records || []
      parkingTotal.value = response.data.total || 0
    })
    .catch(error => {
      console.error('获取停车场列表失败:', error)
      ElMessage.error('获取停车场列表失败')
    })
    .finally(() => {
      parkingListLoading.value = false
    })
}

// 处理筛选
const handleParkingFilter = () => {
  parkingCurrentPage.value = 1;
  parkingFilterForm.page = 1;
  fetchParkingList();
}

// 重置筛选
const resetParkingFilter = () => {
  parkingFilterForm.name = '';
  parkingFilterForm.status = '';
  parkingFilterForm.page = 1;
  parkingCurrentPage.value = 1;
  handleParkingFilter();
}

// 处理分页大小变更
const handleParkingSizeChange = (val) => {
  parkingPageSize.value = val;
  parkingFilterForm.pageSize = val;
  fetchParkingList();
}

// 处理页码变更
const handleParkingCurrentChange = (val) => {
  parkingCurrentPage.value = val;
  parkingFilterForm.page = val;
  fetchParkingList();
}

// 显示添加停车场对话框
const showAddParkingDialog = () => {
  parkingDialog.isEdit = false
  parkingDialog.visible = true
}

// 处理编辑停车场
const handleEditParking = (row) => {
  parkingDialog.isEdit = true
  
  // 复制数据到表单
  Object.keys(parkingForm).forEach(key => {
    if (key in row) {
      parkingForm[key] = row[key]
    }
  })
  
  parkingDialog.visible = true
}

// 重置停车场表单
const resetParkingForm = () => {
  parkingFormRef.value?.resetFields()
  parkingForm.id = ''
  parkingForm.name = ''
  parkingForm.address = ''
  parkingForm.totalSpaces = 100
  parkingForm.availableSpaces = 100
  parkingForm.status = 1
  parkingForm.contactPhone = ''
  parkingForm.businessHours = '24小时营业'
  parkingForm.description = ''
}

// 提交停车场表单
const submitParkingForm = async () => {
  await parkingFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    parkingSubmitting.value = true
    
    try {
      // 检查剩余车位数不大于总车位数
      if (parkingForm.availableSpaces > parkingForm.totalSpaces) {
        parkingForm.availableSpaces = parkingForm.totalSpaces
      }
      
      let response
      
      if (parkingDialog.isEdit) {
        // 编辑现有停车场
        response = await updateParkingLot(parkingForm.id, parkingForm)
      } else {
        // 添加新停车场
        response = await addParkingLot(parkingForm)
      }
      
      const successMsg = parkingDialog.isEdit ? '停车场信息已更新' : '停车场已添加'
      ElMessage.success(successMsg)
      parkingDialog.visible = false
      fetchParkingList()
      
      // 如果正在查看该停车场详情，也更新详情数据
      if (currentParking.value && currentParking.value.id === parkingForm.id) {
        Object.keys(parkingForm).forEach(key => {
          if (key in currentParking.value) {
            currentParking.value[key] = parkingForm[key]
          }
        })
      }
    } catch (error) {
      console.error('提交停车场表单失败', error)
      ElMessage.error(error.response?.data?.message || '操作失败，请重试')
    } finally {
      parkingSubmitting.value = false
    }
  })
}

// 处理切换停车场状态(营业/维护)
const handleToggleParkingStatus = (row) => {
  const newStatus = row.status === 1 ? 2 : 1
  const actionText = newStatus === 1 ? '恢复营业' : '设为维护中'
  
  ElMessageBox.confirm(
    `确定要将停车场"${row.name}"${actionText}吗？`,
    '状态变更',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: newStatus === 1 ? 'success' : 'warning'
    }
  ).then(() => {
    updateParkingLot(row.id, { status: newStatus })
      .then(() => {
        // 更新本地数据
        const index = parkingList.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          parkingList.value[index].status = newStatus
        }
        
        // 如果正在查看该停车场详情，也更新详情数据
        if (currentParking.value && currentParking.value.id === row.id) {
          currentParking.value.status = newStatus
        }
        
        ElMessage.success(`停车场已${actionText}`)
      })
      .catch(error => {
        console.error('更新停车场状态失败', error)
        ElMessage.error(error.response?.data?.message || '操作失败，请重试')
      })
  }).catch(() => {})
}

// 处理关闭停车场
const handleCloseParking = (row) => {
  ElMessageBox.confirm(
    `确定要关闭停车场"${row.name}"吗？关闭后将不再接受新的停车。`,
    '关闭停车场',
    {
      confirmButtonText: '确定关闭',
      cancelButtonText: '取消',
      type: 'danger'
    }
  ).then(() => {
    updateParkingLot(row.id, { status: 0 })
      .then(() => {
        // 更新本地数据
        const index = parkingList.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          parkingList.value[index].status = 0
        }
        
        // 如果正在查看该停车场详情，也更新详情数据
        if (currentParking.value && currentParking.value.id === row.id) {
          currentParking.value.status = 0
        }
        
        ElMessage.success('停车场已关闭')
      })
      .catch(error => {
        console.error('关闭停车场失败', error)
        ElMessage.error(error.response?.data?.message || '操作失败，请重试')
      })
  }).catch(() => {})
}

// 处理点击行，显示停车场详情
const handleParkingRowClick = (row) => {
  currentParking.value = row
  parkingDetailVisible.value = true
}

// 组件挂载时获取数据
onMounted(() => {
  fetchParkingList()
})

// ========== 车位管理相关 ==========
// 车位列表相关
const spaceList = ref([])
const spaceListLoading = ref(false)
const spaceCurrentPage = ref(1)
const spacePageSize = ref(10)
const spaceTotal = ref(0)
const selectedSpaces = ref([])

// 车位筛选表单
const spaceFilterForm = reactive({
  parkingLotId: '',
  area: '',
  spaceNumber: '',
  status: '',
  spaceType: '',
  page: 1,
  pageSize: 10
})

// 车位对话框状态
const spaceDialog = reactive({
  visible: false,
  isEdit: false
})

// 表单引用
const spaceFormRef = ref(null)

// 表单数据
const spaceForm = reactive({
  id: '',
  parkingLotId: '',
  area: '',
  spaceNumber: '',
  spaceType: 0,
  status: 0,
  floor: '1',
  remarks: ''
})

// 表单验证规则
const spaceRules = {
  parkingLotId: [
    { required: true, message: '请选择停车场', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请选择区域', trigger: 'blur' }
  ],
  spaceNumber: [
    { required: true, message: '请输入车位编号', trigger: 'blur' },
    { validator: async (rule, value, callback) => {
      if (!value) {
        callback();
        return;
      }
      
      // 编辑模式且编号未变更时，不需验证
      if (spaceDialog.isEdit && spaceForm.id) {
        const originalSpace = spaceList.value.find(s => s.id === spaceForm.id);
        if (originalSpace && originalSpace.spaceNumber === value) {
          callback();
          return;
        }
      }
      
      if (!spaceForm.parkingLotId) {
        callback(new Error('请先选择停车场'));
        return;
      }
      
      try {
        const params = {
          parkingLotId: spaceForm.parkingLotId,
          spaceNumber: value
        };
        const res = await checkSpaceNumberExists(params);
        if (res.data) {
          callback(new Error('该车位编号已存在'));
        } else {
          callback();
        }
      } catch (error) {
        console.error('验证车位编号失败:', error);
        callback();
      }
    }, trigger: 'blur' }
  ],
  spaceType: [
    { required: true, message: '请选择车位类型', trigger: 'blur' }
  ],
  floor: [
    { required: true, message: '请输入所在楼层', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择车位状态', trigger: 'blur' }
  ]
}

// 提交状态
const spaceSubmitting = ref(false)

// 车位详情抽屉
const spaceDetailDialog = reactive({
  visible: false,
  space: null
})

// 获取车位状态文本
const getSpaceStatusText = (status) => {
  switch (status) {
    case 0: return '空闲'
    case 1: return '已占用'
    case 2: return '已预约'
    case 3: return '维护中'
    case 4: return '已禁用'
    default: return '未知状态'
  }
}

// 获取车位状态类型
const getSpaceStatusColor = (status) => {
  switch (status) {
    case 0: return 'success'
    case 1: return 'warning'
    case 2: return 'info'
    case 3: return 'warning'
    case 4: return 'danger'
    default: return 'info'
  }
}

// 获取车位类型文本
const getSpaceTypeName = (type) => {
  switch (type) {
    case 0: return '普通车位'
    case 1: return '固定车位'
    case 2: return '访客车位'
    default: return '未知类型'
  }
}

// 获取车位类型颜色
const getSpaceTypeColor = (type) => {
  switch (type) {
    case 0: return 'success'
    case 1: return 'warning'
    case 2: return 'info'
    default: return 'info'
  }
}

// 获取车位列表
const fetchSpaceList = () => {
  spaceListLoading.value = true;
  
  const params = {
    page: spaceFilterForm.page,
    size: spaceFilterForm.pageSize
  };
  
  // 添加过滤条件
  if (spaceFilterForm.parkingLotId) {
    params.parkingLotId = spaceFilterForm.parkingLotId;
  }
  
  if (spaceFilterForm.spaceNumber) {
    params.spaceNumber = spaceFilterForm.spaceNumber;
  }
  
  if (spaceFilterForm.area) {
    params.area = spaceFilterForm.area;
  }
  
  if (spaceFilterForm.status !== null && spaceFilterForm.status !== undefined) {
    params.status = spaceFilterForm.status;
  }
  
  // 如果选择了车位类型，添加到参数中
  if (spaceFilterForm.spaceType !== undefined && spaceFilterForm.spaceType !== '') {
    params.spaceType = spaceFilterForm.spaceType;
  }
  
  getParkingSpaceList(params)
    .then(response => {
      spaceList.value = response.data.records || [];
      spaceTotal.value = response.data.total || 0;
    })
    .catch(error => {
      console.error('获取车位列表失败:', error);
      ElMessage.error('获取车位列表失败');
    })
    .finally(() => {
      spaceListLoading.value = false;
    });
}

// 处理车位筛选
const handleSpaceFilter = () => {
  spaceCurrentPage.value = 1;
  spaceFilterForm.page = 1;
  fetchSpaceList();
}

// 重置车位筛选
const resetSpaceFilter = () => {
  spaceFilterForm.parkingLotId = '';
  spaceFilterForm.area = '';
  spaceFilterForm.spaceNumber = '';
  spaceFilterForm.status = '';
  spaceFilterForm.spaceType = '';
  spaceFilterForm.page = 1;
  spaceCurrentPage.value = 1;
  handleSpaceFilter();
}

// 处理分页大小变更
const handleSpaceSizeChange = (val) => {
  spacePageSize.value = val;
  spaceFilterForm.pageSize = val;
  fetchSpaceList();
}

// 处理页码变更
const handleSpaceCurrentChange = (val) => {
  spaceCurrentPage.value = val;
  spaceFilterForm.page = val;
  fetchSpaceList();
}

// 显示添加车位对话框
const showAddSpaceDialog = () => {
  spaceDialog.isEdit = false
  spaceDialog.visible = true
}

// 处理编辑车位
const handleEditSpace = (row) => {
  spaceDialog.isEdit = true
  
  // 复制数据到表单
  Object.keys(spaceForm).forEach(key => {
    if (key in row) {
      spaceForm[key] = row[key]
    }
  })
  
  spaceDialog.visible = true
}

// 重置车位表单
const resetSpaceForm = () => {
  spaceFormRef.value?.resetFields()
  spaceForm.id = ''
  spaceForm.parkingLotId = ''
  spaceForm.area = ''
  spaceForm.spaceNumber = ''
  spaceForm.spaceType = 0
  spaceForm.status = 0
  spaceForm.floor = '1'
  spaceForm.remarks = ''
}

// 提交车位表单
const submitSpaceForm = async () => {
  await spaceFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    spaceSubmitting.value = true
    
    try {
      let response
      
      if (spaceDialog.isEdit) {
        // 编辑现有车位
        response = await updateParkingSpace(spaceForm.id, spaceForm)
      } else {
        // 添加新车位
        response = await addParkingSpace(spaceForm)
      }
      
      const successMsg = spaceDialog.isEdit ? '车位信息已更新' : '车位已添加'
      ElMessage.success(successMsg)
      spaceDialog.visible = false
      fetchSpaceList()
      
      // 如果正在查看该车位详情，也更新详情数据
      if (spaceDetailDialog.space && spaceDetailDialog.space.id === spaceForm.id) {
        Object.keys(spaceForm).forEach(key => {
          if (key in spaceDetailDialog.space) {
            spaceDetailDialog.space[key] = spaceForm[key]
          }
        })
      }
    } catch (error) {
      console.error('提交车位表单失败', error)
      ElMessage.error(error.response?.data?.message || '操作失败，请重试')
    } finally {
      spaceSubmitting.value = false
    }
  })
}

// 处理切换车位状态(空闲/已占用/已预约/维护中/已禁用)
const handleToggleSpaceStatus = (row) => {
  const newStatus = row.status === 0 ? 1 : row.status === 1 ? 2 : row.status === 2 ? 3 : row.status === 3 ? 4 : 0
  const actionText = newStatus === 0 ? '设为空闲' : newStatus === 1 ? '设为已占用' : newStatus === 2 ? '设为已预约' : newStatus === 3 ? '设为维护中' : '设为禁用'
  
  ElMessageBox.confirm(
    `确定要将车位"${row.spaceNumber}"${actionText}吗？`,
    '状态变更',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: newStatus === 0 ? 'success' : newStatus === 1 ? 'success' : newStatus === 2 ? 'success' : newStatus === 3 ? 'warning' : 'danger'
    }
  ).then(() => {
    updateParkingSpace(row.id, { status: newStatus })
      .then(() => {
        // 更新本地数据
        const index = spaceList.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          spaceList.value[index].status = newStatus
        }
        
        // 如果正在查看该车位详情，也更新详情数据
        if (spaceDetailDialog.space && spaceDetailDialog.space.id === row.id) {
          spaceDetailDialog.space.status = newStatus
        }
        
        ElMessage.success(`车位已${actionText}`)
      })
      .catch(error => {
        console.error('更新车位状态失败', error)
        ElMessage.error(error.response?.data?.message || '操作失败，请重试')
      })
  }).catch(() => {})
}

// 处理禁用车位
const handleDisableSpace = (row) => {
  ElMessageBox.confirm(
    `确定要禁用车位"${row.spaceNumber}"吗？禁用后将不再接受新的停车。`,
    '禁用车位',
    {
      confirmButtonText: '确定禁用',
      cancelButtonText: '取消',
      type: 'danger'
    }
  ).then(() => {
    updateParkingSpace(row.id, { status: 4 })
      .then(() => {
        // 更新本地数据
        const index = spaceList.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          spaceList.value[index].status = 4
        }
        
        // 如果正在查看该车位详情，也更新详情数据
        if (spaceDetailDialog.space && spaceDetailDialog.space.id === row.id) {
          spaceDetailDialog.space.status = 4
        }
        
        ElMessage.success('车位已禁用')
      })
      .catch(error => {
        console.error('禁用车位失败', error)
        ElMessage.error(error.response?.data?.message || '操作失败，请重试')
      })
  }).catch(() => {})
}

// 处理车位选择
const handleSpaceSelectionChange = (selection) => {
  selectedSpaces.value = selection
}

// 批量维护
const batchMaintainSpaces = () => {
  if (selectedSpaces.value.length === 0) {
    ElMessage.warning('请选择要维护的车位')
    return
  }
  
  ElMessageBox.confirm(
    `确定要将选中的 ${selectedSpaces.value.length} 个车位设为维护中吗？`,
    '批量维护',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 批量更新车位状态
      const promises = selectedSpaces.value.map(space => 
        updateParkingSpace(space.id, { status: 3 })
      )
      
      await Promise.all(promises)
      
      // 更新本地数据
      selectedSpaces.value.forEach(space => {
        const index = spaceList.value.findIndex(item => item.id === space.id)
        if (index !== -1) {
          spaceList.value[index].status = 3
        }
      })
      
      ElMessage.success(`已将 ${selectedSpaces.value.length} 个车位设为维护中`)
      selectedSpaces.value = []
    } catch (error) {
      console.error('批量维护车位失败', error)
      ElMessage.error('批量维护车位失败，请重试')
    }
  }).catch(() => {})
}

// 批量禁用
const batchDisableSpaces = () => {
  if (selectedSpaces.value.length === 0) {
    ElMessage.warning('请选择要禁用的车位')
    return
  }
  
  ElMessageBox.confirm(
    `确定要禁用选中的 ${selectedSpaces.value.length} 个车位吗？禁用后将不再接受新的停车。`,
    '批量禁用',
    {
      confirmButtonText: '确定禁用',
      cancelButtonText: '取消',
      type: 'danger'
    }
  ).then(async () => {
    try {
      // 批量更新车位状态
      const promises = selectedSpaces.value.map(space => 
        updateParkingSpace(space.id, { status: 4 })
      )
      
      await Promise.all(promises)
      
      // 更新本地数据
      selectedSpaces.value.forEach(space => {
        const index = spaceList.value.findIndex(item => item.id === space.id)
        if (index !== -1) {
          spaceList.value[index].status = 4
        }
      })
      
      ElMessage.success(`已禁用 ${selectedSpaces.value.length} 个车位`)
      selectedSpaces.value = []
    } catch (error) {
      console.error('批量禁用车位失败', error)
      ElMessage.error('批量禁用车位失败，请重试')
    }
  }).catch(() => {})
}

// 处理车位地图相关
const mapDialog = reactive({
  visible: false,
  parkingId: '',
  area: '',
  loading: false,
  parkingLots: [],
  mapSpaces: []
})

// 计算实际存在的区域
const mapAreas = computed(() => {
  return [...new Set(mapDialog.mapSpaces.map(space => space.area))].sort()
})

// 获取车位列表
const getMapSpacesByArea = (area) => {
  return mapDialog.mapSpaces.filter(space => space.area === area)
}

// 获取车位项的CSS类名
const getSpaceItemClass = (status) => {
  return `space-status-${status}`
}

// 处理车位地图相关逻辑
const handleMapParkingChange = () => {
  if (!mapDialog.parkingId) {
    mapDialog.mapSpaces = []
    return
  }

  mapDialog.area = ''
  mapDialog.loading = true
  mapDialog.mapSpaces = []
  
  // 获取选中停车场的车位
  getParkingSpacesByLotId(mapDialog.parkingId)
    .then(response => {
      if (response.data && Array.isArray(response.data)) {
        mapDialog.mapSpaces = response.data
        if (mapDialog.mapSpaces.length === 0) {
          ElMessage.warning('该停车场暂无车位数据')
        }
      } else {
        ElMessage.warning('获取车位数据格式异常')
        mapDialog.mapSpaces = []
      }
    })
    .catch(error => {
      console.error('获取停车场车位失败', error)
      ElMessage.error('获取停车场车位失败')
      mapDialog.mapSpaces = []
    })
    .finally(() => {
      mapDialog.loading = false
    })
}

const handleMapAreaChange = () => {
  // 区域筛选逻辑
}

const handleMapSpaceClick = (space) => {
  spaceDetailDialog.space = space
  spaceDetailDialog.visible = true
}

// 获取车位详情对话框
const showSpaceDetailDialog = (space) => {
  spaceDetailDialog.space = space
  spaceDetailDialog.visible = true
}

// 批量导入相关
const importDialog = reactive({
  visible: false,
  loading: false
})

// 导入表单
const importForm = reactive({
  parkingId: '',
  file: null
})

// 处理文件上传变更
const handleImportFileChange = (file) => {
  importForm.file = file.raw
}

// 提交导入
const submitImport = () => {
  if (!importForm.parkingId) {
    ElMessage.warning('请选择停车场')
    return
  }
  
  if (!importForm.file) {
    ElMessage.warning('请选择导入文件')
    return
  }
  
  const formData = new FormData()
  formData.append('file', importForm.file)
  formData.append('parkingLotId', importForm.parkingId)
  
  batchAddParkingSpaces(formData)
    .then(response => {
      ElMessage.success('批量导入车位成功')
      importDialog.visible = false
      fetchSpaceList()
    })
    .catch(error => {
      ElMessage.error(error.response?.data?.message || '导入失败，请检查文件格式是否正确')
    })
}

// 显示导入对话框
const showImportSpaceDialog = () => {
  importDialog.visible = true
  importForm.parkingId = ''
  importForm.file = null
}

// 显示车位地图对话框
const showSpaceMapDialog = () => {
  mapDialog.visible = true
  // 如果当前已经选择了停车场，则自动使用该停车场
  mapDialog.parkingId = spaceFilterForm.parkingLotId || ''
  mapDialog.area = ''
  mapDialog.loading = false
  mapDialog.mapSpaces = []
  
  // 如果有选择停车场，则自动加载数据
  if (mapDialog.parkingId) {
    handleMapParkingChange()
  }
}

// 计算停车时长
const calculateDuration = (startTime, endTime = null) => {
  if (!startTime) return '未知'
  
  const start = new Date(startTime)
  const end = endTime ? new Date(endTime) : new Date()
  
  const diffMs = end - start
  if (diffMs < 0) return '时间错误'
  
  const diffMins = Math.floor(diffMs / 60000)
  const hours = Math.floor(diffMins / 60)
  const mins = diffMins % 60
  
  if (hours > 24) {
    const days = Math.floor(hours / 24)
    const remainingHours = hours % 24
    return `${days}天${remainingHours}小时${mins}分钟`
  }
  
  return `${hours}小时${mins}分钟`
}

// 地图视图相关数据
const mapView = reactive({
  visible: false,
  loading: false,
  parkingLotId: '',
  parkingLotName: '',
  spaces: [],
  selectedSpace: null,
  selectedArea: ''
})

// 获取特定停车场的车位
const fetchParkingLotSpaces = async (parkingLotId) => {
  if (!parkingLotId) return
  
  mapView.loading = true
  
  try {
    const response = await getParkingSpacesByLotId(parkingLotId)
    mapView.spaces = response.data || []
    // 获取所有唯一区域
    const areas = [...new Set(mapView.spaces.map(space => space.area))]
    mapView.areas = areas
    // 默认选择第一个区域
    mapView.selectedArea = areas.length > 0 ? areas[0] : ''
  } catch (error) {
    console.error('获取停车场车位失败', error)
    ElMessage.error('获取停车场车位失败')
    mapView.spaces = []
    mapView.areas = []
    mapView.selectedArea = ''
  } finally {
    mapView.loading = false
  }
}

// 打开地图视图
const openMapView = (parkingLot) => {
  mapView.visible = true
  mapView.parkingLotId = parkingLot.id
  mapView.parkingLotName = parkingLot.name
  fetchParkingLotSpaces(parkingLot.id)
}

// 计算过滤后的车位列表
const filteredSpaces = computed(() => {
  if (!mapView.selectedArea) return mapView.spaces
  return mapView.spaces.filter(space => space.area === mapView.selectedArea)
})

// 处理车位点击
const handleSpaceClick = (space) => {
  mapView.selectedSpace = space
}

// 关闭车位详情
const closeSpaceDetail = () => {
  mapView.selectedSpace = null
}

</script>

<style scoped>
.parking-management-container {
  min-height: calc(100vh - 180px);
}

.page-header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title h2 {
  margin: 0 0 5px 0;
}

.page-title p {
  margin: 0;
  color: #909399;
}

.page-actions {
  display: flex;
  gap: 10px;
}

.filter-card, .action-card {
  margin-bottom: 20px;
}

.filter-container {
  padding: 5px 0;
}

.parking-list-card, .parking-space-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.space-progress {
  margin-top: 5px;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

/* 停车场详情样式 */
.parking-detail-content {
  padding: 0 20px;
}

.detail-section {
  margin-bottom: 25px;
}

.section-title {
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
}

.info-label {
  width: 100px;
  color: #909399;
}

.info-value {
  flex: 1;
  color: #303133;
}

.spaces-overview {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.space-stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  color: #606266;
  font-size: 14px;
  margin-top: 5px;
}

.space-usage {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.usage-label {
  width: 100px;
  color: #909399;
}

.description-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  min-height: 60px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

/* 车位地图相关样式 */
.map-dialog-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 100px);
  padding: 20px;
}

.map-filter {
  margin-bottom: 20px;
}

.map-status-legend {
  display: flex;
  margin-bottom: 20px;
  gap: 15px;
  flex-wrap: wrap;
  justify-content: center;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 5px 10px;
}

.legend-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
}

.legend-text {
  font-size: 14px;
  color: #606266;
}

.map-container {
  flex: 1;
  background-color: #f5f7fa;
  border-radius: 4px;
  overflow: auto;
  padding: 20px;
}

.map-loading, .map-empty {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.parking-map {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.map-area {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.area-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #dcdfe6;
  color: #303133;
}

.area-spaces {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 20px;
  padding: 10px;
}

.space-item {
  height: 80px;
  border-radius: 8px;
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.space-item:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.space-code {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 4px;
}

.space-plate {
  font-size: 12px;
  background-color: rgba(0, 0, 0, 0.2);
  padding: 2px 6px;
  border-radius: 4px;
}

.space-type-icon {
  position: absolute;
  top: 8px;
  right: 8px;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 4px;
  border-radius: 4px;
}

.space-status-0 {
  background-color: #67c23a;
}

.space-status-1 {
  background-color: #e6a23c;
}

.space-status-2 {
  background-color: #909399;
}

.space-status-3 {
  background-color: #ff9900;
}

.space-status-4 {
  background-color: #f56c6c;
}

.bg-free {
  background-color: #67c23a;
}

.bg-occupied {
  background-color: #e6a23c;
}

.bg-reserved {
  background-color: #909399;
}

.bg-maintenance {
  background-color: #ff9900;
}

.bg-disabled {
  background-color: #f56c6c;
}

.import-container {
  padding: 10px 0;
}

.download-template {
  margin-top: 20px;
  text-align: center;
}

.placeholder-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.under-development-icon {
  color: #409EFF;
}

@media screen and (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .page-actions {
    margin-top: 15px;
    width: 100%;
  }
  
  .filter-form {
    display: flex;
    flex-direction: column;
  }
  
  .filter-form .el-form-item {
    margin-right: 0;
    width: 100%;
  }

  .el-button-group {
    display: flex;
    width: 100%;
  }
  
  .el-button-group .el-button {
    flex: 1;
  }
  
  .spaces-overview {
    flex-direction: column;
    gap: 15px;
  }
  
  .space-stat-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .area-spaces {
    justify-content: center;
  }
}

@media screen and (max-width: 576px) {
  .page-title h2 {
    font-size: 18px;
  }
  
  .page-title p {
    font-size: 12px;
  }
  
  .space-item {
    width: 80px;
    height: 60px;
  }
  
  .el-table {
    font-size: 12px;
  }
}
</style>
